/**
 * 全局音频播放状态管理 Context
 * 用于管理景区音频播放的全局状态，支持全局播放控制条
 */

import React, {
  createContext,
  useContext,
  useState,
  useRef,
  useCallback,
  useEffect,
} from 'react';
import TrackPlayer, { Event, State } from 'react-native-track-player';

const AudioPlayerContext = createContext();

export const AudioPlayerProvider = ({ children }) => {
  // 当前播放的景区信息
  const [currentAttraction, setCurrentAttraction] = useState(null);

  // 播放状态
  const [isPlaying, setIsPlaying] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);

  // 导航信息（用于返回详情页）
  const navigationRef = useRef(null);

  // 进度更新定时器
  const progressIntervalRef = useRef(null);

  // 监听播放状态变化（2.x 版本使用传统事件监听）
  useEffect(() => {
    const playbackStateListener = TrackPlayer.addEventListener(
      Event.PlaybackState,
      async data => {
        const state = data.state;


        // State 是数字枚举
        // STATE_NONE = 0, STATE_READY = 1, STATE_PAUSED = 2, STATE_PLAYING = 3,
        // STATE_STOPPED = 4, STATE_BUFFERING = 6, STATE_ENDED = ?
        // 注意：State.Playing = 3, State.Paused = 2
        if (state === State.Playing || state === 3) {
          setIsPlaying(true);
          setIsPaused(false);
        } else if (state === State.Paused || state === 2) {
          setIsPlaying(false);
          setIsPaused(true);
        } else if (
          state === State.Stopped ||
          state === State.None ||
          state === 0 ||
          state === 4
        ) {
          setIsPlaying(false);
          setIsPaused(false);
        }
      },
    );

    const playbackErrorListener = TrackPlayer.addEventListener(
      Event.PlaybackError,
      error => {
        console.error('❌ TrackPlayer 播放错误:', error);
        setIsPlaying(false);
      },
    );

    return () => {
      playbackStateListener.remove();
      playbackErrorListener.remove();
    };
  }, []);

  // 手动轮询播放进度（2.x 版本没有 useProgress hook）
  useEffect(() => {
    if (isPlaying) {
      progressIntervalRef.current = setInterval(async () => {
        try {
          const position = await TrackPlayer.getPosition();
          const trackDuration = await TrackPlayer.getDuration();

          setCurrentTime(Math.floor(position));
          if (trackDuration > 0) {
            setDuration(Math.floor(trackDuration));
          }
        } catch (error) {
          // 忽略错误
        }
      }, 1000);
    } else {
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
        progressIntervalRef.current = null;
      }
    }

    return () => {
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
      }
    };
  }, [isPlaying]);

  // 监听 Remote 事件（通知栏按钮）
  useEffect(() => {
    const remoteNextListener = TrackPlayer.addEventListener(
      Event.RemoteNext,
      () => {
      },
    );

    const remotePreviousListener = TrackPlayer.addEventListener(
      Event.RemotePrevious,
      () => {
      },
    );

    return () => {
      remoteNextListener.remove();
      remotePreviousListener.remove();
    };
  }, []);

  /**
   * 开始播放（设置当前景区）
   * @param {Object} attraction - 景区对象（必须包含 areaType 用于重新进入）
   * @param {string} audioUrl - 音频URL
   * @param {string} title - 音频标题
   * @param {string} text - 音频文本内容
   */
  const play = useCallback((attraction, audioUrl, title, text) => {
    setCurrentAttraction({
      ...attraction,
      audioUrl,
      audioTitle: title,
      audioText: text,
    });
    setIsPlaying(true);
    setIsPaused(false);
  }, []);

  /**
   * 暂停播放
   */
  const pause = useCallback(() => {
    setIsPaused(true);
    setIsPlaying(false);
  }, []);

  /**
   * 恢复播放（从暂停状态恢复，不改变 currentAttraction）
   */
  const resume = useCallback(() => {
    setIsPlaying(true);
    setIsPaused(false);
  }, []);

  /**
   * 停止播放（清除当前景区）
   */
  const stop = useCallback(() => {
    setCurrentAttraction(null);
    setIsPlaying(false);
    setIsPaused(false);
    setCurrentTime(0);
    setDuration(0);
  }, []);

  /**
   * 更新播放进度
   */
  const updateProgress = useCallback((time, totalDuration) => {
    setCurrentTime(time);
    if (totalDuration > 0) {
      setDuration(totalDuration);
    }
  }, []);

  /**
   * 设置导航引用
   */
  const setNavigation = useCallback(nav => {
    navigationRef.current = nav;
  }, []);

  /**
   * 导航到当前播放的景区详情页
   */
  const navigateToCurrentAttraction = useCallback(() => {
    if (navigationRef.current && currentAttraction) {
      navigationRef.current.navigate('AttractionDetail', {
        attraction: currentAttraction,
        itemId: currentAttraction.id,
        areaType: currentAttraction.areaType, // 传递 areaType，用于 fetchAudioData
      });
    }
  }, [currentAttraction]);

  const value = {
    // 状态
    currentAttraction,
    isPlaying,
    isPaused,
    currentTime,
    duration,

    // 方法
    play,
    pause,
    resume,
    stop,
    updateProgress,
    setNavigation,
    navigateToCurrentAttraction,
  };

  return (
    <AudioPlayerContext.Provider value={value}>
      {children}
    </AudioPlayerContext.Provider>
  );
};

/**
 * 使用全局音频播放状态的 Hook
 */
export const useAudioPlayer = () => {
  const context = useContext(AudioPlayerContext);
  if (!context) {
    throw new Error('useAudioPlayer must be used within AudioPlayerProvider');
  }
  return context;
};

export default AudioPlayerContext;
